<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind" label-width="120px">
      <uni-forms-item name="user_id" label="活动发起者ID" required>
        <uni-easyinput placeholder="活动发起者的ID， 参考`uni-id-users` 表" :disabled="true"
          v-model="formData.user_id"></uni-easyinput>
      </uni-forms-item>
      <!-- 原有表单项添加 :disabled 属性 -->
      <uni-forms-item name="category_id" label="分类">
        <uni-data-picker v-model="formData.category_id" collection="opendb-news-categories"
          field="name as text, _id as value" :disabled="isDisabled"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="title" label="活动名称" required>
        <uni-easyinput placeholder="活动的标题名称" v-model="formData.title" trim="both"
          :disabled="isDisabled"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="avatar" label="封面大图" required>
        <uni-file-picker v-model="formData.avatar" fileMediatype="image" :auto-upload="true" return-type="object"
          :disabled="isDisabled"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="content" label="活动详情大图" required>
        <uni-file-picker v-model="formData.content" fileMediatype="image" :auto-upload="true"
          return-type="object"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="article_status" label="活动状态">
        <uni-data-checkbox v-model="formData.article_status"
          :localdata="formOptions.article_status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="start_time" label="开始时间" required>
        <uni-datetime-picker return-type="timestamp" v-model="formData.start_time"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="end_time" label="结束时间" required>
        <uni-datetime-picker return-type="timestamp" v-model="formData.end_time"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="location_name" label="活动地点名称" required>
        <uni-easyinput placeholder="活动举办地点名称" v-model="formData.location_name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <!-- <uni-forms-item name="last_comment_user_id" label="">
        <uni-easyinput placeholder="最后回复用户 id，参考`uni-id-users` 表"
          v-model="formData.last_comment_user_id"></uni-easyinput>
      </uni-forms-item> -->
      <uni-forms-item name="publish_date" label="发表时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.publish_date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="last_modify_date" label="最后修改时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.last_modify_date"></uni-datetime-picker>
      </uni-forms-item>
      <!-- <uni-forms-item name="coupon_id" label="">
        <uni-easyinput placeholder="关联的优惠卷id, 参考`coupons`表" v-model="formData.coupon_id"></uni-easyinput>
      </uni-forms-item> -->
      <uni-forms-item name="view_count" label="阅读数量">
        <uni-easyinput placeholder="阅读数量" type="number" v-model="formData.view_count"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="like_count" label="参加活动人数">
        <uni-easyinput placeholder="参加活动人数" type="number" v-model="formData.like_count"></uni-easyinput>
      </uni-forms-item>
      <!-- <uni-forms-item name="location_ip" label="活动地点IP">
        <uni-easyinput placeholder="活动地点IP地址" v-model="formData.location_ip"></uni-easyinput>
      </uni-forms-item> -->
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit"
          :disabled="isDisabled">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { validator } from '@/js_sdk/validator/news-articles-image.js';
import { store } from '@/uni_modules/uni-id-pages/common/store'

const db = uniCloud.database();
// const dbCmd = db.command;
const dbCollectionName = 'news-articles-image';

function getValidator(fields) {
  let result = {}
  for (let key in validator) {
    if (fields.includes(key)) {
      result[key] = validator[key]
    }
  }
  return result
}

export default {
  data() {
    let formData = {
      "user_id": "",
      "category_id": "",
      "avatar": "",
      "content": "",
      "article_status": 0,
      "last_comment_user_id": "",
      "publish_date": null,
      "last_modify_date": null,
      "title": "",
      "coupon_id": "",
      "start_time": null,
      "end_time": null,
      "location_name": "",
      "view_count": null,
      "like_count": null,
      "location_ip": ""
    }
    return {
      formData,
      formDataId: '',
      originFormData: null,
      formOptions: {
        "article_status_localdata": [
          {
            "value": 0,
            "text": "草稿箱"
          },
          {
            "value": 1,
            "text": "已发布"
          },
          {
            "value": 2,
            "text": "已过期"
          }
        ]
      },
      rules: {
        ...getValidator(Object.keys(formData))
      }
    }
  },
  onLoad(e) {
    if (e.id) {
      const id = e.id
      this.formDataId = id
      console.log('getDetail id: ', id);
      this.getDetail(id)
    }
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  computed: {
    userId() {
      if (store.hasLogin) {
        return store.userInfo._id
      }
      uni.showModal({
        content: '获取用户信息失败，请重新登录',
        showCancel: false
      })
      return ''
    },
    // 添加新的计算属性
    isDisabled() {
      return this.formData.article_status === 2 && !this.$hasRole('admin')
    },
  },
  methods: {
    goBack() {
      const eventChannel = this.getOpenerEventChannel()
      if (eventChannel && eventChannel.emit) {
        eventChannel.emit('refreshData')
      }
      setTimeout(() => uni.navigateBack(), 500)
    },

    /**
     * 验证表单并提交
     */
    submit() {
      uni.showLoading({
        mask: true
      })
      this.$refs.form.validate().then((res) => {
        return this.submitForm(res)
      }).catch(() => {
      }).finally(() => {
        uni.hideLoading()
      })
    },

    /**
     * 比较表单数据是否有变化
     * @param {Object} newData - 新的表单数据
     * @param {Object} oldData - 原始表单数据
     * @returns {Boolean} - 如果数据有变化返回true，否则返回false
     */
    compareData(newData, oldData) {
      const compareKeys = ['category_id', 'title', 'content', 'article_status', 'avatar',
        'publish_date', 'last_modify_date', 'start_time', 'end_time', 'location_name']
      for (const key of compareKeys) {
        if (key === 'avatar' || key === 'content') {
          const newUrl = newData[key]?.url || newData[key] || ''
          const oldUrl = oldData[key]?.url || oldData[key] || ''
          if (newUrl !== oldUrl) return true
        } else if (newData[key] !== oldData[key]) {
          return true
        }
      }
      return false
    },

    /**
     * 提交表单
     */
    submitForm(value) {
      const submitData = { ...value, user_id: this.userId }
      if (submitData.avatar && submitData.avatar.url) {
        submitData.avatar = submitData.avatar.url
      }
      if (submitData.content && submitData.content.url) {
        submitData.content = submitData.content.url
      }

      // 比较数据是否有变化
      if (!this.compareData(submitData, this.originFormData)) {
        uni.showToast({
          title: '数据未发生变化',
          icon: 'none'
        })
        return false
      }

      // console.log('submitForm submitData: ', submitData);

      // 使用 clientDB 提交数据
      return db.collection(dbCollectionName).doc(this.formDataId).update(submitData).then((res) => {
        uni.showToast({
          title: '修改成功'
        })
        this.getOpenerEventChannel().emit('refreshData')
        setTimeout(() => uni.navigateBack(), 500)
      }).catch((err) => {
        uni.showModal({
          content: err.message || '请求服务失败',
          showCancel: false
        })
      })
    },

    /**
     * 获取表单数据
     * @param {Object} id
     */
    getDetail(id) {
      uni.showLoading({
        mask: true
      })
      db.collection(dbCollectionName).doc(id)
        .field("user_id,category_id,avatar,content,article_status,last_comment_user_id,publish_date,last_modify_date,title,coupon_id,start_time,end_time,location_name,view_count,like_count,location_ip")
        .get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            // 处理图片数据格式
            if (data.avatar) {
              data.avatar = { url: data.avatar }
            }
            if (data.content) {
              data.content = { url: data.content }
            }
            this.formData = { ...data }
            this.originFormData = { ...data }
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
    }
  }
}
</script>
